package com.sto.stoapp.manager;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.sto.stoapp.StoApplication;
import com.sto.stoapp.activity.R;
import com.sto.stoapp.db.StoFilePreference;
import com.sto.stoapp.http.HttpManager;
import com.sto.stoapp.http.URLActions;
import com.sto.stoapp.http.request.SoftUpgradeRequest;
import com.sto.stoapp.http.response.SoftUpgradeResponse;
import com.sto.stoapp.log.ExceptionLog;
import com.sto.stoapp.util.Helper;
import com.sto.stoapp.widget.BaseDialog;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 强制升级apk包
 * 
 * @author Administrator
 * 
 */
@SuppressLint("HandlerLeak")
public class DownApk {

	@SuppressWarnings("unused")
	private static final int ACTION_DEFAULT = 0x0; // 恢复系统默认
	private static final int ACTION_DIS_CANCEL_FINISH = 0X5A; // 都屏蔽
	@SuppressWarnings("unused")
	private static final int ACTION_DIS_CANCEL = 0XA; // 屏蔽取消button
	@SuppressWarnings("unused")
	private static final int ACTION_DIS_FINISH = 0x50; // 屏蔽完成button

	private final int TIME_OUT = 20 * 1000;

	private final int TIME_READ_OUT = 120 * 1000;

	private Context context;

	protected static final int PROGRESS_COUNT = 0;

	private ProgressBar progressBar;

	private TextView downCount, downTv;

	// private AlertDialog dialog;
	private BaseDialog dialog;

	private ExceptionClickListener listener;

	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.what == PROGRESS_COUNT) {
				updateProgress(msg.arg1);
			}
		}

	};

	private void updateProgress(int progress) {
		progressBar.setProgress(progress);
		downCount.setText(progress + "%");
		if (progress == 100) {
			downTv.setText("下载完成");
		}
	}

	public DownApk(Context context) {
		this.context = context;
		View view = LayoutInflater.from(context).inflate(R.layout.down_apk,
				null);
		progressBar = (ProgressBar) view.findViewById(R.id.progress_horizontal);
		downCount = (TextView) view.findViewById(R.id.down_count);
		downTv = (TextView) view.findViewById(R.id.down_tv);
		dialog = new BaseDialog(context);
		dialog.setEnabledKeyEvent(false);
		dialog.showLog(view);

	}

	/**
	 * 取消下载框
	 */
	public void dismiss() {
		dialog.dismiss();
	}

	public void startDown() {

		downNewFile();
	}

	/**
	 * 检测SD卡是否存在
	 * 
	 * @return
	 */
	private boolean ExistSDCard() {
		if (android.os.Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED)) {
			return true;
		} else
			return false;
	}

	// 下载APK包
	private void downNewFile() {
		// final String apkName = uri.substring(uri.lastIndexOf("/") + 1,
		// uri.length());
		if (!ExistSDCard()) {
			Helper.showToast(context, context.getString(R.string.sd_unexists));
			dialog.dismiss();
			return;
		}
		new Thread() {

			public void run() {
				// 锁定cpu不让进入待机
				AlarmAlertWakeLockManager
						.acquireCpuWakeLock(context, "upgrade");
				requstUpgrade();
				AlarmAlertWakeLockManager.releaseCpuLock("upgrade");

			}
		}.start();
	}

	private void requstUpgrade() {

		SoftUpgradeRequest request = new SoftUpgradeRequest(context);
		String requestStr = request.buildToRequestString();
		HttpManager mgr = new HttpManager();
		String responseStr = mgr.doPostClient(requestStr, StoFilePreference
				.getInstance(context).getServerIp()
				+ URLActions.SOFT_UPGRADE_ACTION);

		Gson gs = new Gson();
		SoftUpgradeResponse response = null;

		try {
			response = gs.fromJson(responseStr,
					new TypeToken<SoftUpgradeResponse>() {
					}.getType());
		} catch (JsonSyntaxException e) {
			e.printStackTrace();
		}
		if (response != null) {

			if ("001".equals(response.respCode)) {
				listener.onExceptionClickListener("网络可能出现异常，请重新登录巴枪");
				dialog.dismiss();
			} else if ("10".equals(response.versionCode)
					|| "11".equals(response.versionCode)) {

				HttpDownReqest(StoFilePreference.getInstance(context)
						.getServerIps());
			} else {

				listener.onExceptionClickListener("没有更新");
				dialog.dismiss();
			}

		} else {
			ExceptionLog.writeLog("DownApk SoftUpgradeRequest 发送：", requestStr);
			ExceptionLog.writeLog("DownApk response=null 收到：", responseStr);
			listener.onExceptionClickListener("请求失败，请检查网络是否异常");
			dialog.dismiss();
		}

	}

	private String HttpDownReqest(String uri) {
		String strResult = "";
		Log.d("download uri", uri);
		// String uriAPI = uri;
		// HttpClient client = new DefaultHttpClient();
		HttpClient client = setTimeOutClient();
		HttpGet get = new HttpGet(uri);
		try {
			// 取得HTTP response
			HttpResponse httpResponse = client.execute(get);
			int status = httpResponse.getStatusLine().getStatusCode();
			// 若状态码为200 ok
			if (status == 200) {
				// 取出回应字串
				try {
					HttpEntity entity = httpResponse.getEntity();
					long length = entity.getContentLength();

					InputStream is = entity.getContent();
					FileOutputStream fileOutputStream = null;
					if (is != null) {
						File file = new File(
								Environment.getExternalStorageDirectory(),
								"STO.apk");
						fileOutputStream = new FileOutputStream(file);
						byte[] buf = new byte[1024];
						int ch = -1;
						int times = 0;
						int count = 0;
						while ((ch = is.read(buf)) != -1) {
							fileOutputStream.write(buf, 0, ch);
							count += ch;
							if (times == 30 || (count == length)) {
								Message msg = handler.obtainMessage();
								msg.what = PROGRESS_COUNT;
								msg.arg1 = (int) (count * 100 / length);
								msg.sendToTarget();
								times = 0;
								continue;
							}
							times++;
						}
						openFile(file);
					}
					fileOutputStream.flush();
					if (fileOutputStream != null) {
						fileOutputStream.close();
					}
				} catch (ClientProtocolException e) {
					e.printStackTrace();
					listener.onExceptionClickListener(context
							.getString(R.string.upgrade_failed));
				} catch (IOException e) {
					listener.onExceptionClickListener(context
							.getString(R.string.upgrade_failed));
					e.printStackTrace();
				}
			} else {
				listener.onExceptionClickListener(context
						.getString(R.string.upgrade_failed));
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			listener.onExceptionClickListener(context
					.getString(R.string.upgrade_failed));
		}

		return strResult;
	}

	/**
	 * 设置超时时间和创建httpClient
	 * 
	 * @return
	 */
	private HttpClient setTimeOutClient() {
		HttpParams params = new BasicHttpParams(); // 实例化Post参数对象
		HttpConnectionParams.setConnectionTimeout(params, TIME_OUT);// 设置请求超时
		HttpConnectionParams.setSoTimeout(params, TIME_READ_OUT); // 设置响应超时
		HttpClient client = new DefaultHttpClient(params); // 实例化一个连接对象
		return client;
	}

	private void openFile(File file) {
		dialog.dismiss();

		StoApplication.getStoJni().StoJNI_InstallApkWithSilence(
				file.getPath(),true);

	}

	public void setListener(ExceptionClickListener listener) {
		this.listener = listener;
	}

	/**
	 * 下载异常监听
	 * 
	 * @author mgf
	 * 
	 */
	public interface ExceptionClickListener {

		void onExceptionClickListener(String exception);
	}
}
